<template>
  <a-drawer
    :width="600"
    :visible="show"
    :footer="false"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> {{ data?.type }}组件编辑 </template>
    <div class="seting-box">
      <p class="item-title">内容宽度</p>
      <a-select
        :style="{ width: '320px', background: '#ffffff' }"
        v-model="data.width"
        placeholder="Please select ..."
      >
        <a-option :value="800">Small Width</a-option>
        <a-option :value="952">Default Width</a-option>
        <a-option :value="1208">Middle Width</a-option>
        <a-option :value="1920">Max Width</a-option>
      </a-select>
      <p class="item-title">背景色</p>
      <a-select
        :style="{ width: '320px', background: '#ffffff' }"
        v-model="data.bgColor"
        placeholder="Please select ..."
      >
        <a-option value="#ffffff">White Background</a-option>
        <a-option value="#f8f9fa">Grey Background</a-option>
      </a-select>
      <p class="item-title">章节</p>
      <draggable
        v-model="data.list.sections"
        :component-data="{
          tag: 'div',
          type: 'transition-group',
          name: !drag ? 'flip-list' : null,
        }"
        v-bind="linkDragOptions"
        :disabled="false"
        @start="drag = true"
        @end="drag = false"
        item-key="key"
      >
        <template #item="{ element: link, index: sectionIndex }">
          <div class="draggable_box">
            <div class="drag_top_box">
              <div @click="toggleCollapse(link)">
                <icon-drag-dot style="margin-right: 10px" />{{ link.title }}
              </div>
              <div>
                <icon-drag-arrow class="icon_drag" />
                <icon-delete
                  class="btn-delete"
                  @click.stop="handleDelete(link.key)"
                />
              </div>
            </div>
            <transition name="collapse">
              <div v-show="!isCollapsed(link)">
                <p class="item-title" style="margin-top: 20px">Key</p>
                <a-input
                  style="border: 1px solid #c0c0c0"
                  v-model="link.key"
                  @click.stop
                />
                <span
                  >Key must be formed by lower-case letters (a-z), numbers (0-9)
                  and hyphens (-).</span
                >
                <p class="item-title" style="margin-top: 20px">题目</p>
                <a-input
                  style="border: 1px solid #c0c0c0"
                  v-model="link.title"
                  @click.stop
                />
                <p class="item-title" style="margin-top: 20px">文本</p>
                <a-input
                  style="border: 1px solid #c0c0c0"
                  v-model="link.text"
                  @click.stop
                />
                <p class="item-title" style="margin-top: 20px">按钮</p>
                <a-input
                  style="border: 1px solid #c0c0c0"
                  v-model="link.button"
                  @click.stop
                />
                <p class="item-title" style="margin-top: 20px">Publications</p>
                <div class="sub_draggable_box">
                  <draggable
                    v-model="link.publications"
                    :component-data="{
                      tag: 'div',
                      type: 'transition-group',
                      name: !dragSub ? 'flip-list' : null,
                    }"
                    v-bind="publicationDragOptions"
                    :disabled="false"
                    @start="dragSub = true"
                    @end="dragSub = false"
                    item-key="id"
                  >
                    <template #item="{ element: item }">
                      <div class="draggable_box">
                        <div class="drag_top_box">
                          <div @click.stop="toggleCollapseSub(item)">
                            <icon-drag-dot style="margin-right: 10px" />
                            {{ item.title }}
                          </div>
                          <div>
                            <icon-drag-arrow class="icon_drag" />
                            <icon-delete
                              class="btn-delete"
                              @click.stop="handleDeleteSub(item.id, link.key)"
                            />
                          </div>
                        </div>
                        <transition name="collapse">
                          <div v-show="!isCollapsedSub(item)">
                            <p class="item-title" style="margin-top: 20px">
                              Title
                            </p>
                            <a-input
                              style="border: 1px solid #f1eeee"
                              v-model="item.title"
                            />
                            <p class="item-title" style="margin-top: 20px">
                              图片
                            </p>
                            <img class="item-img" :src="item.image" />
                            <div class="item-uplaod flex items-center">
                              <a-input
                                v-model="item.image"
                                placeholder="请输入图片链接"
                                allow-clear
                                style="border: 1px solid #c0c0c0"
                              />
                              <Upload
                                v-model="item.image"
                                :name="`Publications_${item.id}`"
                                button-class="fit-content"
                              />
                            </div>
                            <!-- 文件链接 -->
                            <p class="item-title" style="margin-top: 20px">
                              文件链接
                            </p>
                            <img class="item-img" :src="item.fileUrl" />
                            <div class="item-uplaod flex items-center">
                              <a-input
                                v-model="item.fileUrl"
                                placeholder="请输入图片链接"
                                allow-clear
                                style="border: 1px solid #c0c0c0"
                              />
                              <Upload
                                v-model="item.fileUrl"
                                :name="`Publications_${item.id}`"
                                button-class="fit-content"
                              />
                            </div>
                          </div>
                        </transition>
                      </div> </template
                  ></draggable>
                  <!-- 新增按钮 -->
                  <p v-if="!link.publications">No items found.</p>
                  <a-button
                    style="margin-top: 10px; margin-left: 5px"
                    type="primary"
                    @click="addPublication(sectionIndex)"
                    >新增Publications</a-button
                  >
                </div>

                <!-- Publications -->
              </div>
            </transition>
          </div>
        </template>
      </draggable>
      <!-- 新增按钮 -->
      <a-button
        style="margin-top: 10px; margin-left: 5px"
        type="primary"
        @click="addSection"
        >新增Section</a-button
      >
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import Upload from '@/common/Upload/index.vue'
import { ref, computed, nextTick, watch, defineAsyncComponent } from "vue";
import { randomString, generateFormattedKey } from "@/utils/common";
// 动态导入 draggable，避免 SSR 问题
const draggable = defineAsyncComponent(() => import("vuedraggable"));
const linkDragOptions = computed(() => ({
  animation: 200,
  group: "links", // 链接专用分组
  disabled: false,
  ghostClass: "ghost",
}));

// 内层Publications拖拽选项配置
const publicationDragOptions = computed(() => ({
  animation: 200,
  group: "publications", // Publications专用分组
  disabled: false,
  ghostClass: "ghost",
}));

// 拖拽相关状态
const drag = ref(false);
const dragSub = ref(false); // 内层拖拽状态
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },

  data: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:show"]);

const handleCancel = () => {
  emit("update:show", false);
};
const collapsedItems = ref(new Set());
const collapsedItemsSub = ref(new Set());

// 监听数据变化，设置默认折叠状态
const isInit = ref(false);
watch(
  () => props.data?.list?.sections,
  (newSections: any) => {
    if (newSections && Array.isArray(newSections) && !isInit.value) {
      isInit.value = true;
      // 将所有sections的key添加到collapsedItems中，实现默认折叠
      const allKeys = newSections.map((section) => section.key);
      collapsedItems.value = new Set(allKeys);

      // 将所有publications子项目的id添加到collapsedItemsSub中，实现默认折叠
      const allPublicationIds: string[] = [];
      newSections.forEach((section) => {
        if (section.publications && Array.isArray(section.publications)) {
          section.publications.forEach((publication: any) => {
            if (publication.id) {
              allPublicationIds.push(publication.id);
            }
          });
        }
      });
      collapsedItemsSub.value = new Set(allPublicationIds);
    }
  },
  { immediate: true, deep: true }
);
const addSection = () => {
  props.data.list.sections.push({
    key: generateFormattedKey(),
    title: "new Section",
    text: "",
    button: "View all",
  });
};
const addPublication = (sectionIndex: number) => {
  // 给指定索引的section添加新的publication
  const newPublication = {
    id: randomString(10),
    title: "new Publications",
    image: "",
    fileUrl: "",
  };
  // 获取对应的section
  const section = props.data.list.sections[sectionIndex];

  // 确保publications数组存在
  if (!section.publications) {
    section.publications = [];
  }

  // 添加到指定section的publications数组中
  section.publications.push(newPublication);
};

const toggleCollapseSub = (item: any) => {
  // 如果当前项目已经展开，则折叠它
  if (!collapsedItemsSub.value.has(item.id)) {
    collapsedItemsSub.value.add(item.id);
  } else {
    // 如果当前项目是折叠的，则展开它并折叠所有其他项目
    // 首先获取所有Publications子项目的ID
    const allPublicationIds: string[] = [];
    props.data.list.sections.forEach((section: any) => {
      if (section.publications && Array.isArray(section.publications)) {
        section.publications.forEach((publication: any) => {
          if (publication.id) {
            allPublicationIds.push(publication.id);
          }
        });
      }
    });

    // 将所有项目设为折叠状态
    collapsedItemsSub.value = new Set(allPublicationIds);
    // 然后展开当前点击的项目
    collapsedItemsSub.value.delete(item.id);
  }
};
const handleDeleteSub = (id: string, sectionKey: string) => {
  // 找到对应的section
  const section = props.data.list.sections.find(
    (s: any) => s.key === sectionKey
  );
  if (section && section.publications) {
    // 从publications数组中删除指定id的项目
    section.publications = section.publications.filter(
      (item: any) => item.id !== id
    );
  }
};

// 切换指定项的折叠状态
const toggleCollapse = (item: any) => {
  // 如果当前项目已经展开，则折叠它
  if (!collapsedItems.value.has(item.key)) {
    collapsedItems.value.add(item.key);
  } else {
    // 如果当前项目是折叠的，则展开它并折叠所有其他项目
    // 首先获取所有章节的key
    const allSectionKeys: string[] = [];
    props.data.list.sections.forEach((section: any) => {
      if (section.key) {
        allSectionKeys.push(section.key);
      }
    });

    // 将所有章节设为折叠状态
    collapsedItems.value = new Set(allSectionKeys);
    // 然后展开当前点击的章节
    collapsedItems.value.delete(item.key);
  }
};
const handleDelete = (key: string) => {
  props.data.list.sections = props.data.list.sections.filter(
    (item: any) => item.key !== key
  );
};
// 检查指定项是否已折叠
const isCollapsed = (item: any) => {
  return collapsedItems.value.has(item.key);
};

// 检查内层项目是否已折叠
const isCollapsedSub = (item: any) => {
  return collapsedItemsSub.value.has(item.id);
};
const handleClickAdd = () => {
  const detail = props.data;
  detail.data.push({
    name: "New Contact",
    title: "",
    region: "",
    link: "",
    key: randomString(),
  });
  nextTick(() => {
    if (typeof document !== "undefined") {
      const drawerContent = document.querySelector(".arco-drawer-body");
      if (drawerContent) {
        drawerContent.scrollTop = drawerContent.scrollHeight;
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.sub_draggable_box {
  border: 1px solid rgb(221, 221, 221);
  border-radius: 6px;
  padding: 8px;
}
.icon_drag {
  margin-right: 15px;
  cursor: pointer;
  &:hover {
    opacity: 0.8;
  }
}
.drag_top_box {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  display: flex;
  justify-content: space-between;
  padding: 8px;
  cursor: pointer;
  background-color: #f5f5f5;
  border-radius: 4px;

  &:hover {
    background-color: #e8e8e8;
  }
}

// 折叠动画
.collapse-enter-active,
.collapse-leave-active {
  transition: all 0.3s ease;
  max-height: 500px;
  overflow: hidden;
  opacity: 1;
}

.collapse-enter-from,
.collapse-leave-to {
  max-height: 0;
  opacity: 0;
  overflow: hidden;
}

.draggable_box {
  margin-bottom: 25px;
  background: #fff;
  padding: 10px;
  position: relative;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  &:hover {
    transform: translateY(-2px);
  }
}
// :deep(.arco-input-wrapper) {
//   background-color: #ffffff;
// }
.item-title {
  padding: 12px 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  margin-top: 10px;
}
.item-img {
  height: 100px;
}
.seting-box {
  padding: 20px;
  background: #f0f2f5;
  border-radius: 3px;
  // .arco-input-wrapper {
  //   background: #ffffff;
  // }
}
.setting-content {
  .setting-header {
    padding-bottom: 12px;

    .header-title {
      width: 120px;
      padding-right: 12px;
      text-align: right;
    }
  }

  .setting-body {
    margin-top: 12px;

    .setting-item {
      position: relative;
      padding: 16px 12px;
      background: #f0f2f5;
      border-radius: 8px;
      margin-bottom: 20px;

      .btn-group {
        position: absolute;
        right: 0;
        top: 0;
        display: flex;
        align-items: center;
        padding: 4px;

        .btn-delete {
          padding: 4px;
          font-size: 24px;
          cursor: pointer;
        }
      }

      .item-name {
        font-size: 16px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #fff;
      }

      .item-title {
        padding: 12px 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }

      .arco-input-wrapper {
        background: #fff;
      }

      .item-button {
        position: relative;
        padding: 12px 8px 4px;
        background: #fff;
        border-radius: 4px;
        margin: 4px 0;
        transition: all 0.3s ease;

        &.draggable-item {          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
          }

          // 当禁用拖拽时，不显示拖拽效果
          &.sortable-disabled {
            cursor: default;

            &:hover {
              box-shadow: none;
              transform: none;
            }
          }
        }

        .arco-input-wrapper {
          background: #f2f3f5;
        }
      }

      // 拖拽相关样式
      .flip-list-move {
        transition: transform 0.5s;
      }

      .no-move {
        transition: transform 0s;
      }

      .ghost {
        opacity: 0.5;
        background: #c8ebfb;
      }

      .list-group {
        min-height: 20px;
      }

      .list-group-item {      }

      .list-group-item i {
        cursor: pointer;
      }

      .item-action {
        padding: 10px 0;

        .action-text {
          width: 150px;
          margin-right: 8px;
        }
      }

      .item-add-btn {
        display: inline-block;
        padding: 2px 8px;
        margin-top: 5px;
        font-size: 11px;
        color: #165dff;
        border-radius: 4px;
        font-weight: 600;
        border: 1px solid #165dff;
        cursor: pointer;
      }

      .item-img {
        margin-top: 12px;
        height: 160px;
      }

      .fit-content {
        width: fit-content;
      }

      .item-img-list {
        .img-list-item {
          margin: 4px 0;
          position: relative;
          padding: 8px;
          border-radius: 4px;
          transition: all 0.3s ease;
          background: #fff;
          border-radius: 4px;

          &.draggable-item {            &:hover {
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              transform: translateY(-1px);
            }

            // 当禁用拖拽时，不显示拖拽效果
            &.sortable-disabled {
              cursor: default;

              &:hover {
                box-shadow: none;
                transform: none;
              }
            }
          }

          .arco-input-wrapper {
            background: #f2f3f5;
          }

          .img-drag-handle {
            top: 0 !important;
          }
        }

        .item-img-box {
          margin-right: 12px;
          position: relative;
          width: 133px;
          height: 100px;

          .item-img-dlete {
            position: absolute;
            padding: 8px;
            font-size: 32px;
            top: -16px;
            right: -16px;
            color: red;
            cursor: pointer;
          }
        }

        .small-img {
          margin: 0;
          height: 100px;
          object-fit: cover;
        }

        .item-right {
          padding-top: 24px;
        }
      }
    }
  }

  .drag-handle {
    padding: 4px;
    cursor: grab;
    padding: 4px;
    border-radius: 4px;

    &:hover {
      background-color: #f0f2f5;
    }

    &:active {
      cursor: grabbing;
    }

    .drag-icon {
      font-size: 16px;
      color: #86909c;
    }
  }
}
.item-img {
  height: 100px;
}

/* Publications组件样式 */
.publications-mt-small {
  margin-top: 0.5rem;
}

.publications-flex-center {
  display: flex;
  align-items: center;
}

.publications-fit-content {
  width: fit-content;
}
.seting-box {
  padding: 20px;
  background: #f0f2f5;
  border-radius: 3px;
  .arco-input-wrapper {
    background: #ffffff;
  }
}
.setting-content {
  .setting-header {
    padding-bottom: 12px;

    .header-title {
      width: 120px;
      padding-right: 12px;
      text-align: right;
    }
  }

  .setting-body {
    margin-top: 12px;

    .setting-item {
      position: relative;
      padding: 16px 12px;
      background: #f0f2f5;
      border-radius: 8px;
      margin-bottom: 20px;

      .btn-group {
        position: absolute;
        right: 0;
        top: 0;
        display: flex;
        align-items: center;
        padding: 4px;

        .btn-delete {
          padding: 4px;
          font-size: 24px;
          cursor: pointer;
        }
      }

      .item-name {
        font-size: 16px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #fff;
      }

      .item-title {
        padding: 12px 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }

      .arco-input-wrapper {
        background: #fff;
      }

      .item-button {
        position: relative;
        padding: 12px 8px 4px;
        background: #fff;
        border-radius: 4px;
        margin: 4px 0;
        transition: all 0.3s ease;

        &.draggable-item {          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
          }

          // 当禁用拖拽时，不显示拖拽效果
          &.sortable-disabled {
            cursor: default;

            &:hover {
              box-shadow: none;
              transform: none;
            }
          }
        }

        .arco-input-wrapper {
          background: #f2f3f5;
        }
      }

      // 拖拽相关样式
      .flip-list-move {
        transition: transform 0.5s;
      }

      .no-move {
        transition: transform 0s;
      }

      .ghost {
        opacity: 0.5;
        background: #c8ebfb;
      }

      .list-group {
        min-height: 20px;
      }

      .list-group-item {      }

      .list-group-item i {
        cursor: pointer;
      }

      .item-action {
        padding: 10px 0;

        .action-text {
          width: 150px;
          margin-right: 8px;
        }
      }

      .item-add-btn {
        display: inline-block;
        padding: 2px 8px;
        margin-top: 5px;
        font-size: 11px;
        color: #165dff;
        border-radius: 4px;
        font-weight: 600;
        border: 1px solid #165dff;
        cursor: pointer;
      }

      .item-img {
        margin-top: 12px;
        height: 160px;
      }

      .fit-content {
        width: fit-content;
      }

      .item-img-list {
        .img-list-item {
          margin: 4px 0;
          position: relative;
          padding: 8px;
          border-radius: 4px;
          transition: all 0.3s ease;
          background: #fff;
          border-radius: 4px;

          &.draggable-item {            &:hover {
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              transform: translateY(-1px);
            }

            // 当禁用拖拽时，不显示拖拽效果
            &.sortable-disabled {
              cursor: default;

              &:hover {
                box-shadow: none;
                transform: none;
              }
            }
          }

          .arco-input-wrapper {
            background: #f2f3f5;
          }

          .img-drag-handle {
            top: 0 !important;
          }
        }

        .item-img-box {
          margin-right: 12px;
          position: relative;
          width: 133px;
          height: 100px;

          .item-img-dlete {
            position: absolute;
            padding: 8px;
            font-size: 32px;
            top: -16px;
            right: -16px;
            color: red;
            cursor: pointer;
          }
        }

        .small-img {
          margin: 0;
          height: 100px;
          object-fit: cover;
        }

        .item-right {
          padding-top: 24px;
        }
      }
    }
  }

  .drag-handle {
    padding: 4px;
    cursor: grab;
    padding: 4px;
    border-radius: 4px;

    &:hover {
      background-color: #f0f2f5;
    }

    &:active {
      cursor: grabbing;
    }

    .drag-icon {
      font-size: 16px;
      color: #86909c;
      // color: #f1eeee;
    }
  }
}
</style>
